package com.tyqx.hashchainbackend.controller;

import com.tyqx.hashchainbackend.service.*;
import com.tyqx.hashchainbean.module.SysRole;
import com.tyqx.hashchainbean.module.TrackUser;
import com.tyqx.hashchainbean.vo.IdVO;
import com.tyqx.hashchainbean.vo.SysRoleVO;
import hashchainutil.common.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

@Controller
@RequestMapping("/sysRole")
public class SysRoleController {

    @Resource
    SysRoleService roleService;

    @Resource
    SysRolePermissionService permissionService;

    @Resource
    SysRoleResourceService roleResourceService;

    @Resource
    SysPermissionService sysPermissionService;

    @Resource
    SysResourceService sysResourceService;

    /**
     * 查询角色信息
     *
     * @param roleName
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/queryPage", method = RequestMethod.GET)
    @ResponseBody
    public BackendPage<List<SysRole>> queryPage(@RequestParam(value = "roleName", required = false) String roleName,
                                                @RequestParam("page") Integer pageIndex,
                                                @RequestParam("limit") Integer pageSize) {
        // 构建参数
        Map<String, Object> prams = new HashMap<>();

        if (EmptyUtils.isNotEmpty(roleName)) {
            prams.put("roleName", roleName);
        }

        try {
            BackendPage<List<SysRole>> listPage = roleService.queryPageByMap(prams, pageIndex, pageSize);
            return listPage;
        } catch (Exception e) {
            e.printStackTrace();
            return new BackendPage<>("查询异常");
        }
    }

    @RequestMapping(value = "/queryRoleByUserId", method = RequestMethod.GET)
    @ResponseBody
    public List<SysRoleVO> queryRoleByUserId(@RequestParam(value = "userId") Long userId){
        return roleService.getAllByUserId(userId);
    }

    /**
     * 添加角色信息
     *
     * @param sysRole
     * @return
     */
    @RequestMapping(value = "/saveRole", method = RequestMethod.GET)
    @ResponseBody
    public Dto saveRole(SysRole sysRole) {
        Subject currentUser = SecurityUtils.getSubject();
        TrackUser user = (TrackUser) currentUser.getSession().getAttribute("trackUser");
        sysRole.setRoleCreatedBy(user.getId().toString());
        try {
            if (roleService.save(sysRole))
                return DtoUtil.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DtoUtil.returnFail("添加异常", "100000");
    }

    /**
     * 修改角色信息
     *
     * @param sysRole
     * @return
     */
    @RequestMapping(value = "/modifyRole", method = RequestMethod.GET)
    @ResponseBody
    public Dto modifyRole(SysRole sysRole) {
        Subject currentUser = SecurityUtils.getSubject();
        TrackUser user = (TrackUser) currentUser.getSession().getAttribute("trackUser");
        sysRole.setRoleCreatedBy(user.getId().toString());
        try {
            if (roleService.modify(sysRole))
                return DtoUtil.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DtoUtil.returnFail("修改异常", "100000");
    }

    /**
     * 给角色分配权限
     *
     * @return
     */
    @RequestMapping("/allocationPermissions")
    @ResponseBody
    public Dto allocationPermissions(IdVO idVO) {
        Subject currentUser = SecurityUtils.getSubject();
        TrackUser user = (TrackUser) currentUser.getSession().getAttribute("trackUser");
        idVO.setUserId(Long.valueOf(user.getId()));
        try {
            List<Long> preIdList = new ArrayList<>();
            for (Long id : idVO.getPreIdList()) {
                preIdList.add(id);
                List<Long> parentIds = sysPermissionService.queryPerId(id);
                if (null != parentIds) {
                    for (Long parentId : parentIds) {
                        preIdList.add(parentId);
                    }
                }
            }
            idVO.setPreIdList(preIdList);
            if (permissionService.save(idVO)) {
                return DtoUtil.returnSuccess();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DtoUtil.returnFail("分配失败", "100000");
    }

    /**
     * 自动生成角色Key
     *
     * @return
     */
    @RequestMapping("/generateRoleKey")
    @ResponseBody
    public Dto queryRoleKey() {
        String uPwd = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        String pwd = null;
        try {
            pwd = RC4Util.encry_RC4_string(String.format("%07d", null), uPwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DtoUtil.returnDataSuccess(pwd,"");
    }
}

